import { Component, OnInit, Input, ElementRef, forwardRef, ViewChild } from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { NzMessageService } from 'ng-zorro-antd';
@Component({
    template: `
        <div class="clain-image-upload" [ngStyle]="{ width: clainWidth, height: clainHeight }">
            <input
                class="file"
                type="file"
				name="{{ clName }}"
				#filevalue
                accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"
                (change)="fileChangeEvent($event)"
            />
            <i *ngIf="value" class="remove-image" (click)="removeValue()">╳</i>
            <div class="clain-upload-btn-box">
                <a target="_blank" href="{{ value }}" *ngIf="value">
                    <img src="{{ value }}" class="upload-image" />
                </a>
                <div class="clain-upload-btn" *ngIf="!value && !showLoading" (click)="clickUpload($event)">
                    <font size="6">+</font>
                    <br /><span>{{ clTitle }}</span>
                </div>
			</div>
			<div class="image-cropper-box" *ngIf="showCropper">
				<div class="image-cropper-box-bg"></div>
				<div class="image-cropper-box-body">
					<div class="body-top">
						<div class="body-top-left">
							<image-cropper
							[imageChangedEvent]="imageChangedEvent"
							[maintainAspectRatio]="true"
							[aspectRatio]="4 / 4"
							[resizeToWidth]="300"
							[onlyScaleDown]="true"
							format="png,jpeg"
							(imageCropped)="imageCropped($event)"
							(imageLoaded)="imageLoaded()"
							(loadImageFailed)="loadImageFailed()"
							></image-cropper>
						</div>
						<div class="body-top-right">
							<img [src]="cropperUrl" class="header-large" />
							<img [src]="cropperUrl" class="header-middle" />
							<img [src]="cropperUrl" class="header-small" />
						</div>
					</div>
					<div class="body-bottom">
						<button class="sure" (click)="uploadImage()">{{'cz.save'|translate}}</button>
						<button class="cancel" (click)="cancel()">{{'cz.cancel'|translate}}</button>
					</div>
					
				</div>
			</div>
        </div>
    `,
    selector: "clain-header-cropper",
    styleUrls: ["header-cropper.scss"],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => ClainHeaderCropperComponent),
            multi: true
        }
    ]
})
export class ClainHeaderCropperComponent implements OnInit, ControlValueAccessor {
	@ViewChild('filevalue')
	filevalue:ElementRef;
    @Input()
    private clName = "image";
    @Input()
    private clainWidth = "235px";
    @Input()
    private clainHeight = "150px";
    @Input()
    private clMultiple: Boolean = false;
    @Input()
    private clSize = 1;
    @Input()
    private clUrl = "/api/updateImage.do";
    @Input()
    private value: string;
    @Input()
    private clTitle = "上传头像";
    private showLoading: Boolean = false;
	private ev = 0;
	private showCropper = false;
	private imageChangedEvent;
	private cropperUrl;
	private cropperImage;
    constructor(private nzMessageService: NzMessageService, private el: ElementRef) {}
    propagateChange = (_: any) => {};
    writeValue(value: string) {
        if (value) {
            this.value = value;
        }
    }

    registerOnChange(fn: any) {
        this.propagateChange = fn;
    }

    registerOnTouched(fn: any) {}

    ngOnInit() {
        if (this.clMultiple) {
            this.el.nativeElement.querySelector(".file").setAttribute("multiple", "multiple");
        }
	}
	fileChangeEvent(event: any){
		console.log(event);
        if (event.target.files.length > 0) {
			this.imageChangedEvent = event;
			this.showCropper = true;
        }
	}
	imageLoaded(event){
		console.log("b:",event);
	}
	loadImageFailed(event){
		console.log("c:",event);
	}
	imageCropped($event){
		console.log("a:",$event);
		this.cropperImage = $event.file;
		var a = new FileReader();
		a.readAsDataURL($event.file);
		a.onload = (e:any)=>{
			this.cropperUrl = e.target.result;
			console.log(a);
		};
	}

	cancel(){
		this.filevalue.nativeElement.value = null;
		this.showCropper = false;
	}
    /**
     * uploadImage
     */
    public uploadImage(e) {
        const file = new File([this.cropperImage], 'a.png', {type: this.cropperImage.type});
        const { size, type } = file;
        if (size > this.clSize * 1024 * 1024) {
            this.nzMessageService.error("图片大小超过限制,不能上传超过" + this.clSize + "MB的图片");
            return;
        }
        const formData: any = new FormData();
        const xhr = new XMLHttpRequest();
        // formData.append('file', files);
        formData.append(this.clName, file);
        xhr.upload.onprogress = ev => {
            this.ev = parseInt((100 * ev.loaded) / ev.total + "");
        };
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                this.showLoading = false;
                if (xhr.status === 200) {
                    const data = JSON.parse(xhr.response);
                    this.value = data.data.url;
					this.propagateChange(data.data.url);
					this.showCropper = false;
					this.filevalue.nativeElement.value = null;
                } else {
					this.filevalue.nativeElement.value = null;
					this.showCropper = false;
                }
            }
        };

        xhr.open("POST", this.clUrl, true);
        console.log(localStorage.getItem("token"));
        if (localStorage.getItem("token")) {
            const token = localStorage.getItem("token");
            xhr.setRequestHeader("Authorization", "Bearer " + token);
        }
        xhr.send(formData);
        this.showLoading = true;
    }
    public clickUpload() {
        this.el.nativeElement.querySelector(".file").click();
    }
    /**
     * removeValue 删除当前上传图片
     */
    public removeValue() {
        this.value = "";
        this.propagateChange("");
        this.el.nativeElement.querySelector(".file").value = null;
    }
    public getObjectURL(file: File): string {
        return window.URL.createObjectURL(file);
    }
}
